package org.jetlinks.community.mstn.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetlinks.community.dashboard.web.request.DashboardMeasurementRequest;
import org.jetlinks.community.device.entity.DeviceInstanceEntity;
import org.jetlinks.community.device.entity.DeviceProperty;
import org.jetlinks.community.device.service.LocalDeviceInstanceService;
import org.jetlinks.community.gateway.annotation.Subscribe;
import org.jetlinks.core.message.event.EventMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;

@Slf4j
@Component
public class MstnDeviceMessageHandler {

    @Autowired
    private LocalDeviceInstanceService deviceInstanceService;

    @Autowired
    private MstnSystemService mstnSystemService;


    /**
     * 子设备数据上报完成
     * @param message
     * @return
     */
    @Subscribe("/device/*/*/message/event/gatewayDone")
    public Mono<Void> handleGatewayUploadDone(EventMessage message) {
        LinkedHashMap map = (LinkedHashMap) message.getData();
        String value = (String) map.get("test");
        String gatewayId = message.getDeviceId();
        //遍历网关下子设备1分钟内是否收到数据
        Flux<DeviceInstanceEntity> devices = deviceInstanceService.createQuery().where(DeviceInstanceEntity::getParentId, gatewayId).fetch();
        Flux<DashboardMeasurementRequest> requests = devices.map(device -> mstnSystemService.initRequest(device.getId(), device.getProductId(), new ArrayList<>((Collections.singleton(value)))));

        return mstnSystemService.getDeviceProperty(requests).collectList()
            .flatMap(list -> {
                for (DeviceProperty device : list) {
                    if (Long.valueOf(device.getCreateTime()) == null ||
                        device.getCreateTime() == 0 ) {
                        log.info("数据为空:{}", device.getDeviceId());
                    } else if (System.currentTimeMillis() - device.getCreateTime() > 60000) {
                        log.info("数据超时:{}", device.getDeviceId());
                    } else {
                        log.info("数据不为空:{} ========》{}", device.getDeviceId(), device.getValue());
                    }

                }
                log.info("收到子设备数据上报完成事件,子设备数量:{}", list.size());
                return Mono.empty();
            });
    }
}
